<template>
  <view class="coupon-edit-container">
    <!-- 表单内容 -->
    <view class="form-container">
      <u-form ref="couponForm" :model="couponForm" labelWidth="200">
        <view class="form-section">
          <view class="section-title">基础信息</view>

          <u-form-item label="优惠券名称" prop="name">
            <u-input v-model="couponForm.name" placeholder="请输入优惠券名称" />
          </u-form-item>

          <u-form-item label="优惠券类型" prop="couponType">
            <u-radio-group v-model="couponForm.couponType" placement="row">
              <u-radio :size="30" labelSize="30" iconSize="20" label="固定金额" :name="1"></u-radio>
              <u-radio :size="30" labelSize="30" iconSize="20" label="折扣比例" :name="2"></u-radio>
            </u-radio-group>
          </u-form-item>

          <u-form-item v-if="couponForm.couponType === 1" label="抵扣金额" prop="money">
            <u-input v-model="couponForm.money" type="digit" placeholder="请输入抵扣金额">
              <text slot="prefix">¥</text>
            </u-input>
          </u-form-item>

          <u-form-item v-if="couponForm.couponType === 2" label="折扣比例" prop="deductionBl">
            <u-input v-model="couponForm.deductionBl" type="digit" placeholder="请输入折扣比例(如8.5表示8.5折)">
              <text slot="suffix">折</text>
            </u-input>
          </u-form-item>

          <!--      <u-form-item label="是否限量" prop="isLimited">
            <u-radio-group v-model="couponForm.isLimited" placement="row">
              <u-radio :size="30" labelSize="30" iconSize="20" label="否" :name="false"></u-radio>
              <u-radio :size="30" labelSize="30" iconSize="20" label="是" :name="true"></u-radio>
            </u-radio-group>
          </u-form-item> -->

          <u-form-item v-if="couponForm.isLimited" label="发放总量" prop="total">
            <u-input v-model="couponForm.total" type="number" placeholder="请输入发放总量">
              <text slot="suffix">张</text>
            </u-input>
          </u-form-item>

          <!--    <u-form-item label="最低消费" prop="minPrice">
            <u-input v-model="couponForm.minPrice" type="digit" placeholder="请输入最低消费金额，0为不限制">
              <text slot="prefix">¥</text>
            </u-input>
          </u-form-item> -->
        </view>

        <view class="form-section">
          <view class="section-title">时间设置</view>

          <!-- 隐藏领取是否限时选项 -->
          <!-- <u-form-item label="领取是否限时" prop="isForever">
            <u-radio-group v-model="couponForm.isForever" placement="row">
              <u-radio :size="30" labelSize="30" iconSize="20" label="否" :name="false"></u-radio>
              <u-radio :size="30" labelSize="30" iconSize="20" label="是" :name="true"></u-radio>
            </u-radio-group>
          </u-form-item> -->

          <!-- 隐藏领取时间选择 -->
          <!-- <view v-if="couponForm.isForever">
            <u-form-item label="领取开始时间" prop="receiveStartTime" @click="selectReceiveStartTime">
              <u-input v-model="couponForm.receiveStartTime" placeholder="请选择领取开始时间" disabled />
              <u-icon name="arrow-right" slot="right" />
            </u-form-item>

            <u-form-item label="领取结束时间" prop="receiveEndTime" @click="selectReceiveEndTime">
              <u-input v-model="couponForm.receiveEndTime" placeholder="请选择领取结束时间" disabled />
              <u-icon name="arrow-right" slot="right" />
            </u-form-item>
          </view> -->

          <!--     <u-form-item label="使用时间类型" prop="isFixedTime">
            <u-radio-group v-model="couponForm.isFixedTime" placement="row">
              <u-radio :size="30" labelSize="30" iconSize="20" label="固定时间" :name="true"></u-radio>
              <u-radio :size="30" labelSize="30" iconSize="20" label="领取后天数" :name="false"></u-radio>
            </u-radio-group>
          </u-form-item> -->

          <view v-if="couponForm.isFixedTime">
            <u-form-item label="使用开始时间" prop="useStartTime" @click="selectUseStartTime">
              <u-input v-model="couponForm.useStartTime" placeholder="请选择使用开始时间" disabled />
              <u-icon name="arrow-right" slot="right" />
            </u-form-item>

            <u-form-item label="使用结束时间" prop="useEndTime" @click="selectUseEndTime">
              <u-input v-model="couponForm.useEndTime" placeholder="请选择使用结束时间" disabled />
              <u-icon name="arrow-right" slot="right" />
            </u-form-item>
          </view>

          <u-form-item v-else label="有效天数" prop="day">
            <u-input v-model="couponForm.day" type="number" placeholder="请输入领取后有效天数">
              <text slot="suffix">天</text>
            </u-input>
          </u-form-item>
        </view>

        <view class="form-section">
          <view class="section-title">其他设置</view>

          <!--   <u-form-item label="优惠券领取方式" prop="type">
            <u-radio-group v-model="couponForm.type" placement="row">
              <u-radio :size="30" labelSize="30" iconSize="20" label="手动领取" :name="1"></u-radio>
              <u-radio :size="30" labelSize="30" iconSize="20" label="新人券" :name="2"></u-radio>
              <u-radio :size="30" labelSize="30" iconSize="20" label="赠送券" :name="3"></u-radio>
            </u-radio-group>
          </u-form-item> -->

          <!--     <u-form-item label="使用类型" prop="useType">
            <u-radio-group v-model="couponForm.useType" placement="row">
              <u-radio :size="30" labelSize="30" iconSize="20" label="全场通用" :name="1"></u-radio>
              <u-radio :size="30" labelSize="30" iconSize="20" label="商品券" :name="2"></u-radio>
              <u-radio :size="30" labelSize="30" iconSize="20" label="品类券" :name="3"></u-radio>
            </u-radio-group>
          </u-form-item> -->

          <u-form-item label="关联活动" prop="ebMerActivityId" @click="selectActivity">
            <u-input v-model="couponForm.activityName" placeholder="请选择关联活动" disabled />
            <u-icon name="arrow-right" slot="right" />
          </u-form-item>

          <u-form-item label="排序" prop="sort">
            <u-input v-model="couponForm.sort" type="number" placeholder="请输入排序值，数字越大越靠前" />
          </u-form-item>

          <u-form-item label="状态" prop="status">
            <u-radio-group v-model="couponForm.status" placement="row">
              <u-radio :size="30" labelSize="30" iconSize="20" label="关闭" :name="false"></u-radio>
              <u-radio :size="30" labelSize="30" iconSize="20" label="开启" :name="true"></u-radio>
            </u-radio-group>
          </u-form-item>
        </view>
      </u-form>
    </view>

    <!-- 底部操作按钮 -->
    <view class="footer-actions">
      <u-button type="primary" @click="saveCoupon">保存</u-button>
      <u-button v-if="isEdit" type="error" @click="deleteCoupon">删除</u-button>
    </view>

    <!-- 时间选择器 -->
    <u-datetime-picker :show="showTimePicker" mode="date" v-model="selectedTime" @confirm="confirmTime" @cancel="cancelTimePicker"></u-datetime-picker>

    <!-- 活动选择弹窗 -->
    <u-popup :show="showActivityPopup" mode="bottom" border-radius="20">
      <view class="activity-popup">
        <view class="activity-header">
          <text class="header-title">选择关联活动</text>
          <u-icon name="close" size="24" @click="showActivityPopup = false" />
        </view>

        <view class="activity-list">
          <view class="activity-item" v-for="(activity, index) in activityList" :key="activity.id" @click="selectActivityItem(activity)">
            <text>{{ activity.name }}</text>
            <u-icon name="checkmark" v-if="activity.id === couponForm.ebMerActivityId" color="#2979ff" />
          </view>
        </view>

        <view class="activity-footer" v-if="loadingActivities">
          <u-loading-icon mode="circle" size="24" />
          <text class="loading-text">加载中...</text>
        </view>
      </view>
    </u-popup>
  </view>
</template>

<script>
import { activitylist, addCoupon } from '../../utils/request_sh.js';

export default {
  data() {
    return {
      isEdit: false,
      couponId: null,
      couponForm: {
        name: '', // 优惠券名称
        couponType: 1, // 前端使用，1-固定金额 2-折扣比例
        money: '', // 抵扣金额
        deductionBl: '', // 折扣比例
        isLimited: false, // 是否限量
        total: '', // 发放总量
        minPrice: '0', // 最低消费
        isForever: false, // 是否固定领取时间
        receiveStartTime: '', // 领取开始时间
        receiveEndTime: '', // 领取结束时间
        isFixedTime: true, // 是否固定使用时间
        useStartTime: '', // 使用开始时间
        useEndTime: '', // 使用结束时间
        day: '', // 有效天数
        type: 1, // 优惠券类型 1 手动领取, 2 新人券, 3 赠送券
        useType: 1, // 使用类型 1 全场通用, 2 商品券, 3 品类券
        ebMerActivityId: '', // 关联活动id
        activityName: '', // 关联活动名称（前端展示用）
        sort: 0, // 排序
        status: true // 状态
      },
      showTimePicker: false,
      selectedTime: Number(new Date()),
      timePickerField: '', // 记录当前正在设置的时间字段
      showActivityPopup: false,
      activityList: [],
      loadingActivities: false,
      userInfo: {}
    };
  },

  onLoad(options) {
    this.userInfo = uni.getStorageSync('userInfo');

    if (options.id) {
      this.isEdit = true;
      this.couponId = options.id;
      this.loadCouponData();
    }

    // 设置默认的领取时间：开始时间为昨天，结束时间为十年后
    this.setDefaultReceiveTime();
  },

  onShow() {
    // 如果是从活动选择页面返回，刷新活动列表
    if (this.showActivityPopup) {
      this.loadActivityList();
    }
  },

  methods: {
    // 设置默认领取时间
    setDefaultReceiveTime() {
      const now = new Date();
      // 开始时间为昨天
      const startDate = new Date(now);
      startDate.setDate(now.getDate() - 1);

      // 结束时间为十年后
      const endDate = new Date(now);
      endDate.setFullYear(now.getFullYear() + 10);

      this.couponForm.receiveStartTime = this.formatDate(startDate.getTime());
      this.couponForm.receiveEndTime = this.formatDate(endDate.getTime());
    },

    // 加载优惠券数据（编辑模式）
    loadCouponData() {
      // 模拟加载数据
      this.couponForm = {
        name: '新人专享券',
        couponType: 1,
        money: '50',
        deductionBl: '',
        isLimited: true,
        total: '1000',
        minPrice: '0',
        isForever: false,
        receiveStartTime: '',
        receiveEndTime: '',
        isFixedTime: true,
        useStartTime: '',
        useEndTime: '',
        day: '',
        type: 2,
        useType: 1,
        ebMerActivityId: 1,
        activityName: '新用户专享',
        sort: 0,
        status: true
      };

      // 设置默认的领取时间
      this.setDefaultReceiveTime();
    },

    // 选择领取开始时间
    selectReceiveStartTime() {
      this.timePickerField = 'receiveStartTime';
      this.selectedTime = this.couponForm.receiveStartTime ? new Date(this.couponForm.receiveStartTime).getTime() : new Date().getTime();
      this.showTimePicker = true;
    },

    // 选择领取结束时间
    selectReceiveEndTime() {
      this.timePickerField = 'receiveEndTime';
      this.selectedTime = this.couponForm.receiveEndTime ? new Date(this.couponForm.receiveEndTime).getTime() : new Date().getTime();
      this.showTimePicker = true;
    },

    // 选择使用开始时间
    selectUseStartTime() {
      this.timePickerField = 'useStartTime';
      this.selectedTime = this.couponForm.useStartTime ? new Date(this.couponForm.useStartTime).getTime() : new Date().getTime();
      this.showTimePicker = true;
    },

    // 选择使用结束时间
    selectUseEndTime() {
      this.timePickerField = 'useEndTime';
      this.selectedTime = this.couponForm.useEndTime ? new Date(this.couponForm.useEndTime).getTime() : new Date().getTime();
      this.showTimePicker = true;
    },

    // 确认时间选择
    confirmTime(e) {
      // 格式化为 yyyy-MM-dd
      this.couponForm[this.timePickerField] = this.formatDate(e.value);
      this.showTimePicker = false;
    },

    // 取消时间选择
    cancelTimePicker() {
      this.showTimePicker = false;
    },

    // 格式化日期为 yyyy-MM-dd
    formatDate(timestamp) {
      const date = new Date(timestamp);
      const year = date.getFullYear();
      const month = (date.getMonth() + 1).toString().padStart(2, '0');
      const day = date.getDate().toString().padStart(2, '0');
      return `${year}-${month}-${day}`;
    },

    // 选择活动
    selectActivity() {
      this.showActivityPopup = true;
      if (this.activityList.length === 0) {
        this.loadActivityList();
      }
    },

    // 加载活动列表
    loadActivityList() {
      if (!this.userInfo.merId) return;

      this.loadingActivities = true;
      const params = {
        userRightComand: 'shanghuAdmin',
        pageNum: 1,
        pageSize: 100,
        ebMerId: this.userInfo.merId,
        isVendorActivity: this.userInfo.isVendor
      };

      activitylist(params)
        .then((res) => {
          this.activityList = res.rows || [];
        })
        .catch((err) => {
          console.error('获取活动列表失败:', err);
          uni.showToast({
            title: '获取活动列表失败',
            icon: 'none'
          });
        })
        .finally(() => {
          this.loadingActivities = false;
        });
    },

    // 选择具体的活动项
    selectActivityItem(activity) {
      this.couponForm.ebMerActivityId = activity.id;
      this.couponForm.activityName = activity.name;
      this.showActivityPopup = false;
    },

    // 保存优惠券
    saveCoupon() {
      // 表单验证
      if (!this.couponForm.name) {
        uni.showToast({ title: '请输入优惠券名称', icon: 'none' });
        return;
      }

      if (this.couponForm.name.length > 64) {
        uni.showToast({ title: '优惠券名称长度不能超过64个字符', icon: 'none' });
        return;
      }

      if (this.couponForm.couponType === 1) {
        if (!this.couponForm.money || parseFloat(this.couponForm.money) <= 0) {
          uni.showToast({ title: '请输入正确的抵扣金额', icon: 'none' });
          return;
        }

        if (parseFloat(this.couponForm.money) > 99999.99) {
          uni.showToast({ title: '优惠券面值不能大于99999.99', icon: 'none' });
          return;
        }
      } else if (this.couponForm.couponType === 2) {
        if (!this.couponForm.deductionBl || parseFloat(this.couponForm.deductionBl) <= 0 || parseFloat(this.couponForm.deductionBl) > 10) {
          uni.showToast({ title: '请输入正确的折扣比例(0-10之间)', icon: 'none' });
          return;
        }
      }

      if (this.couponForm.isLimited) {
        if (!this.couponForm.total || parseInt(this.couponForm.total) <= 0) {
          uni.showToast({ title: '请输入正确的发放总量', icon: 'none' });
          return;
        }
      }

      // 移除对领取时间的验证，因为现在是自动设置的
      /*
      if (!this.couponForm.isForever) {
        if (!this.couponForm.receiveStartTime) {
          uni.showToast({ title: '请选择领取开始时间', icon: 'none' });
          return;
        }

        if (!this.couponForm.receiveEndTime) {
          uni.showToast({ title: '请选择领取结束时间', icon: 'none' });
          return;
        }

        // 验证时间逻辑
        if (new Date(this.couponForm.receiveStartTime) > new Date(this.couponForm.receiveEndTime)) {
          uni.showToast({ title: '领取开始时间不能晚于结束时间', icon: 'none' });
          return;
        }
      }
      */

      if (this.couponForm.isFixedTime) {
        if (!this.couponForm.useStartTime) {
          uni.showToast({ title: '请选择使用开始时间', icon: 'none' });
          return;
        }

        if (!this.couponForm.useEndTime) {
          uni.showToast({ title: '请选择使用结束时间', icon: 'none' });
          return;
        }

        // 验证时间逻辑
        if (new Date(this.couponForm.useStartTime) > new Date(this.couponForm.useEndTime)) {
          uni.showToast({ title: '使用开始时间不能晚于结束时间', icon: 'none' });
          return;
        }
      } else {
        if (!this.couponForm.day || parseInt(this.couponForm.day) <= 0) {
          uni.showToast({ title: '请输入有效天数', icon: 'none' });
          return;
        }

        if (parseInt(this.couponForm.day) > 999) {
          uni.showToast({ title: '天数不能超过999天', icon: 'none' });
          return;
        }
      }

      if (this.couponForm.sort === '' || this.couponForm.sort < 0) {
        uni.showToast({ title: '排序不能小于0', icon: 'none' });
        return;
      }

      if (!this.couponForm.ebMerActivityId) {
        uni.showToast({ title: '请选择关联活动', icon: 'none' });
        return;
      }

      // 构造提交数据
      const submitData = {
        name: this.couponForm.name,
        money: this.couponForm.couponType === 1 ? this.couponForm.money : '0',
        deductionBl: this.couponForm.couponType === 2 ? this.couponForm.deductionBl : null,
        isLimited: this.couponForm.isLimited,
        total: this.couponForm.isLimited ? this.couponForm.total : null,
        minPrice: this.couponForm.minPrice || '0',
        isForever: this.couponForm.isForever,
        receiveStartTime: this.couponForm.receiveStartTime,
        receiveEndTime: this.couponForm.receiveEndTime,
        isFixedTime: this.couponForm.isFixedTime,
        useStartTime: this.couponForm.isFixedTime ? this.couponForm.useStartTime || null : null,
        useEndTime: this.couponForm.isFixedTime ? this.couponForm.useEndTime || null : null,
        day: this.couponForm.isFixedTime ? null : this.couponForm.day,
        type: /* this.couponForm.type */ 1,
        useType: /*  this.couponForm.useType */ 4,
        ebMerActivityId: this.couponForm.ebMerActivityId,
        sort: this.couponForm.sort,
        status: this.couponForm.status,
        ebMerId: this.userInfo.merId,
        isVendor: this.userInfo.isVendor,
        couponType: this.couponForm.couponType
      };

      // 如果是编辑模式，添加ID
      if (this.isEdit) {
        submitData.id = this.couponId;
      }

      console.log('提交数据:', submitData);

      addCoupon(submitData)
        .then((res) => {
          if (res.code == 200) {
            uni.showToast({
              title: this.isEdit ? '编辑成功' : '添加成功',
              icon: 'success'
            });
            // 返回上一页
            setTimeout(() => {
              uni.navigateBack();
            }, 1000);
          } else {
            uni.showToast({
              title: res.message,
              icon: 'none'
            });
          }
        })
        .catch((err) => {
          console.error('保存优惠券失败:', err);
          uni.showToast({
            title: '保存失败，请稍后重试',
            icon: 'none'
          });
        });
    },

    // 删除优惠券
    deleteCoupon() {
      uni.showModal({
        title: '确认删除',
        content: '确定要删除这张优惠券吗？',
        success: (res) => {
          if (res.confirm) {
            // 模拟删除操作
            uni.showToast({
              title: '删除成功',
              icon: 'success'
            });

            // 返回上一页
            setTimeout(() => {
              uni.navigateBack();
            }, 1000);
          }
        }
      });
    }
  }
};
</script>

<style lang="scss" scoped>
.coupon-edit-container {
  width: 100%;
  min-height: 100vh;
  background-color: #f5f5f5;
  padding: 20rpx;
  box-sizing: border-box;
  padding-bottom: 120rpx;
}

.page-header {
  background-color: #fff;
  border-radius: 16rpx;
  padding: 30rpx;
  margin-bottom: 20rpx;
  box-shadow: 0 4rpx 16rpx rgba(0, 0, 0, 0.05);

  .page-title {
    display: block;
    font-size: 36rpx;
    font-weight: bold;
    color: #333;
    text-align: center;
  }
}

.form-container {
  background-color: #fff;
  border-radius: 16rpx;
  padding: 30rpx;
  box-shadow: 0 4rpx 16rpx rgba(0, 0, 0, 0.05);

  .form-section {
    margin-bottom: 30rpx;

    .section-title {
      font-size: 32rpx;
      font-weight: bold;
      color: #333;
      margin-bottom: 20rpx;
      padding-bottom: 10rpx;
      border-bottom: 1rpx solid #f0f0f0;
    }

    ::v-deep .u-form-item {
      margin-bottom: 20rpx;
    }

    ::v-deep .u-radio-group {
      flex: 1;
    }
  }
}

.footer-actions {
  position: fixed;
  bottom: 60rpx;
  left: 50%;
  transform: translateX(-50%);
  width: 80%;
  display: flex;
  gap: 20rpx;

  .u-button {
    flex: 1;
  }
}

.activity-popup {
  .activity-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 30rpx;
    border-bottom: 1rpx solid #eee;

    .header-title {
      font-size: 32rpx;
      font-weight: bold;
      color: #333;
    }
  }

  .activity-list {
    max-height: 600rpx;
    overflow-y: auto;

    .activity-item {
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding: 30rpx;
      border-bottom: 1rpx solid #eee;

      &:last-child {
        border-bottom: none;
      }
    }
  }

  .activity-footer {
    display: flex;
    justify-content: center;
    align-items: center;
    padding: 30rpx;

    .loading-text {
      margin-left: 16rpx;
      font-size: 28rpx;
      color: #999;
    }
  }
}
</style>
